<template>
  <div class="home-container">
    <div class="container">
      <div class="user-dropdown" ref="dropdownRef">
        <button class="user-btn" @click="toggleDropdown">{{ username.slice(0, 5) }}</button>
        <transition name="fade">
          <div v-if="dropdownOpen" class="dropdown-menu">
            <div class="dropdown-balance">
              <span class="balance-label">余额</span>
              <span class="balance-amount">{{ money }}元</span>
            </div>
            <div class="menu-divider"></div>
            <div class="dropdown-item" @click="logout">退出登录</div>
          </div>
        </transition>
      </div>
      <button class="add-btn" @click="showAddDialog = true">发红包</button>
      <button class="rank-btn" @click="showRankDialog = true">排行榜</button>
      <div class="tab-bar">
        <div :class="['tab', tabActive === 'hall' ? 'active' : '']" @click="switchTab('hall')">大厅红包</div>
        <div :class="['tab', tabActive === 'mine' ? 'active' : '']" @click="switchTab('mine')">我的红包</div>
      </div>
      <div class="title-container">
        <h2>{{ tabActive === 'hall' ? '大厅红包列表' : '我的红包列表' }}</h2>
        <button class="refresh-btn" @click="refreshList" title="刷新列表">
          <i class="refresh-icon">↻</i>
        </button>
      </div>
      <div class="red-list">
        <div v-for="item in redList" :key="item.key" class="red-item">
          <div class="header-container">
            <span class="red-username">{{ item.username }}</span>
            <div class="red-time">{{ item.createTime ? formatTime(item.createTime) : '' }}</div>
            <button 
              v-if="tabActive === 'mine'" 
              class="cancel-btn" 
              @click.stop="cancelRed(item)" 
              title="撤销红包"
            >
              <i class="cancel-icon">×</i>
            </button>
          </div>
          <div class="red-amount" @click="openRed(item)">金额：{{ item.remainMoney }}</div>
          <div class="red-count" @click="openRed(item)">数量：{{ item.remainSize }}</div>
          <div class="red-id" @click="openRed(item)">ID：{{ item.id }}</div>
        </div>
      </div>
      <RedPacketDialog v-if="showDialog" :redInfo="currentRed" @close="showDialog = false" @taken="handleTaken" @updateMoney="money = $event"/>
      <AddRedPacketDialog v-if="showAddDialog" @close="showAddDialog = false" @success="fetchList" @updateMoney="money = $event"/>
      
      <!-- 添加自定义弹窗 -->
      <div v-if="showMsg" class="custom-alert-mask">
        <div class="custom-alert-box">
          <div class="custom-alert-content">{{ msgContent }}</div>
          <button class="custom-alert-btn" @click="showMsg = false">知道了</button>
        </div>
      </div>
      <div v-if="showRankDialog" class="rank-dialog-mask">
        <div class="rank-dialog-box">
          <div class="rank-dialog-title">用户金额排行榜</div>
          <button class="rank-dialog-close" @click="showRankDialog = false">×</button>
          <ul class="rank-dialog-list">
            <li v-for="(user, idx) in rankList" :key="user.username" :class="['rank-dialog-item', idx < 3 ? 'top' + (idx+1) : '']">
              <span class="rank-dialog-index">{{ idx+1 }}</span>
              <span class="rank-dialog-username">{{ user.username }}</span>
              <span class="rank-dialog-money">{{ user.money }} 元</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, watch} from 'vue';
import {useRouter} from 'vue-router';
import axios from '../axios';
import RedPacketDialog from '../components/RedPacketDialog.vue';
import AddRedPacketDialog from '../components/AddRedPacketDialog.vue';

const router = useRouter();
const redList = ref([]);
const showDialog = ref(false);
const currentRed = ref(null);
const showAddDialog = ref(false);
const tabActive = ref('hall');
const username = ref('');
const dropdownOpen = ref(false);
const dropdownRef = ref(null);
const money = ref(0);
const showMsg = ref(false);
const msgContent = ref('');
const showRankDialog = ref(false);
const rankList = ref([]);

const fetchList = async () => {
  try {
    let url = tabActive.value === 'hall' ? '/red-package/list' : '/red-package/my-list';
    const res = await axios.get(url);
    if (res.data.code === 200) {
      redList.value = res.data.data || [];
    } else {
      showAlert('获取红包列表失败');
    }
  } catch (e) {
    showAlert('接口异常');
  }
};

const switchTab = (tab) => {
  if (tabActive.value !== tab) {
    tabActive.value = tab;
    fetchList();
  }
};

const openRed = async (item) => {
  try {
    const res = await axios.get('/red-package/get', {params: {redId: item.id}});
    if (res.data.code === 200) {
      currentRed.value = {...item, ...res.data.data};
      showDialog.value = true;
    } else {
      showAlert('获取红包详情失败');
    }
  } catch (e) {
    showAlert('接口异常');
  }
};

const handleTaken = () => {
  fetchList();
};

const logout = async () => {
  try {
    await axios.get('/user/logout');
  } catch (e) {
    // 忽略异常，保证登出流程
  } finally {
    localStorage.removeItem('token');
    router.replace('/login');
  }
};

const fetchUserInfo = async () => {
  try {
    const res = await axios.get('/user/getInfo');
    if (res.data.code === 200) {
      username.value = res.data.data?.username || '';
      money.value = res.data.data?.money || 0;
    }
  } catch (e) {
    // 可选：错误处理
  }
};

function toggleDropdown() {
  dropdownOpen.value = !dropdownOpen.value;
}

function handleClickOutside(event) {
  if (dropdownRef.value && !dropdownRef.value.contains(event.target)) {
    dropdownOpen.value = false;
  }
}

const cancelRed = async (item) => {
  try {
    const res = await axios.get('/red-package/cancel', { 
      params: { redId: item.id }
    });
    if (res.data.code === 200) {
      fetchList();
      fetchUserInfo(); // 刷新用户余额
    } else {
      showAlert(res.data.msg || '撤销失败');
    }
  } catch (e) {
    showAlert('接口异常');
  }
};

function showAlert(msg) {
  msgContent.value = msg;
  showMsg.value = true;
}

const refreshList = async () => {
  const btn = document.querySelector('.refresh-btn');
  if (btn) btn.classList.add('refreshing');
  await fetchList();
  if (btn) {
    setTimeout(() => {
      btn.classList.remove('refreshing');
    }, 500);
  }
};

function formatTime(time) {
  if (!time) return '';
  // 假设time为时间戳或ISO字符串
  const date = new Date(time);
  const y = date.getFullYear();
  const m = (date.getMonth() + 1).toString().padStart(2, '0');
  const d = date.getDate().toString().padStart(2, '0');
  const h = date.getHours().toString().padStart(2, '0');
  const min = date.getMinutes().toString().padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${min}`;
}

const fetchRank = async () => {
  try {
    const res = await axios.get('/red-package/rank');
    if (res.data.code === 200) {
      rankList.value = res.data.data || [];
    }
  } catch (e) {
    // 可选：错误处理
  }
};

watch(showRankDialog, (val) => {
  if (val) fetchRank();
});

onMounted(() => {
  fetchUserInfo();
  fetchList();
  document.addEventListener('mousedown', handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener('mousedown', handleClickOutside);
});
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding-top: 32px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 32px;
  box-sizing: border-box;
  position: relative;
}

.user-info {
  position: absolute;
  top: 24px;
  right: 270px;
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #409eff;
  z-index: 10;
  background: #f2f8ff;
  border-radius: 8px;
  padding: 7px 18px 7px 14px;
  font-weight: 600;
  box-shadow: 0 2px 8px #409eff11;
}

.user-label {
  color: #888;
  margin-right: 4px;
  font-weight: 400;
}

.user-name {
  color: #409eff;
  font-weight: 700;
}

.user-dropdown {
  position: absolute;
  top: 24px;
  right: 32px;
  z-index: 20;
  display: inline-block;
}

.user-btn {
  background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 10px 28px;
  font-size: 17px;
  font-weight: 700;
  cursor: pointer;
  box-shadow: 0 4px 16px #409eff33, 0 1.5px 0 #fff inset;
  transition: background 0.2s, box-shadow 0.2s, transform 0.1s;
  letter-spacing: 1px;
  position: relative;
}

.user-btn:hover, .user-btn:focus {
  background: linear-gradient(90deg, #3076c9 0%, #409eff 100%);
}

.dropdown-menu {
  position: absolute;
  top: 120%;
  right: 0;
  background: #fff;
  border: none;
  border-radius: 10px;
  box-shadow: 0 8px 32px #409eff22, 0 1.5px 0 #fff inset;
  min-width: 140px;
  padding: 8px 0;
  margin-top: 6px;
  text-align: left;
  animation: fadeIn 0.18s;
}

.dropdown-arrow {
  position: absolute;
  top: -10px;
  right: 18px;
  width: 18px;
  height: 10px;
  overflow: hidden;
}
.dropdown-arrow::after {
  content: '';
  display: block;
  width: 18px;
  height: 18px;
  background: #fff;
  box-shadow: 0 2px 8px #409eff22;
  transform: rotate(45deg);
  position: absolute;
  top: 2px;
  left: 0;
  border-radius: 4px 0 0 0;
}

.dropdown-item {
  padding: 8px 24px;
  color: #f56c6c;
  font-size: 15px;
  cursor: pointer;
  border-radius: 6px;
  margin: 0 4px;
  transition: background 0.2s, color 0.2s;
  font-weight: 600;
  text-align: center;
  white-space: nowrap;
}
.menu-divider {
  height: 1px;
  background: #eee;
  margin: 4px 0;
}
.dropdown-item:hover {
  background: #f7f8fa;
  color: #e24444;
}
.balance-label {
  color: #666;
  font-size: 13px;
}
.balance-amount {
  color: #409eff;
  font-size: 16px;
  font-weight: bold;
}
.dropdown-balance {
  padding: 8px 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.18s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-8px);}
  to { opacity: 1; transform: translateY(0);}
}

.add-btn {
  position: absolute;
  top: 24px;
  right: 160px;
  background: linear-gradient(90deg, #67c23a 0%, #b3e19d 100%);
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 10px 28px;
  cursor: pointer;
  font-size: 17px;
  font-weight: 700;
  box-shadow: 0 4px 16px #67c23a33, 0 1.5px 0 #fff inset;
  transition: background 0.2s, box-shadow 0.2s, transform 0.1s;
  z-index: 10;
  letter-spacing: 1px;
  overflow: hidden;
}

.add-btn::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  border-radius: 8px;
  box-shadow: 0 0 0 0 #fff0, 0 0 8px 2px #b3e19d44 inset;
  opacity: 0;
  transition: opacity 0.2s;
  pointer-events: none;
}

.add-btn:hover {
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  box-shadow: 0 8px 24px #67c23a44, 0 1.5px 0 #fff inset;
  transform: translateY(-2px) scale(1.03);
}

.add-btn:hover::after {
  opacity: 1;
}

.tab-bar {
  display: flex;
  gap: 24px;
  margin: 0 0 18px 0;
  padding-top: 10px;
}

.tab {
  font-size: 18px;
  font-weight: 600;
  color: #888;
  padding: 8px 32px;
  border-radius: 6px 6px 0 0;
  background: #f2f3f5;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}

.tab.active {
  color: #409eff;
  background: #fff;
  box-shadow: 0 -2px 8px #409eff11;
}

.title-container {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 28px;
}

.title-container h2 {
  margin: 0;
}

.refresh-btn {
  background: #fff;
  border: 1.5px solid #409eff33;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  color: #409eff;
}

.refresh-btn:hover {
  background: #f0f7ff;
  border-color: #409eff66;
  transform: scale(1.05);
}

.refresh-icon {
  font-size: 20px;
  font-style: normal;
  transition: transform 0.5s;
}

.refreshing .refresh-icon {
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.red-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: flex-start;
}

.red-item {
  position: relative;
  background: #fff;
  border: 1px solid #e0e3e8;
  border-radius: 8px;
  box-shadow: 0 2px 8px #409eff11;
  padding: 20px 24px;
  min-width: 220px;
  max-width: 260px;
  flex: 1 1 220px;
  cursor: pointer;
  transition: box-shadow 0.2s, border 0.2s;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.red-item:hover {
  box-shadow: 0 4px 16px #409eff22;
  border: 1.5px solid #409eff;
}

.red-amount {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  margin-top: 18px;
}

.red-count, .red-id {
  font-size: 15px;
  color: #666;
}

.header-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 36px;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  pointer-events: none;
  z-index: 2;
}

.red-username {
  position: absolute;
  top: 8px;
  left: 16px;
  font-size: 13px;
  color: #409eff;
  background: #f2f8ff;
  padding: 2px 10px;
  border-radius: 10px;
  font-weight: 500;
  pointer-events: auto;
}

.red-time {
  position: absolute;
  top: 8px;
  right: 48px;
  font-size: 13px;
  color: #67c23a;
  background: #f2f8ff;
  padding: 2px 10px;
  border-radius: 10px;
  font-weight: 500;
  box-shadow: 0 1px 4px #409eff11;
  letter-spacing: 1px;
  pointer-events: auto;
}

.cancel-btn {
  position: absolute;
  top: 6px;
  right: 16px;
  width: 20px;
  height: 20px;
  padding: 0;
  border: none;
  border-radius: 50%;
  background: #fff0f0;
  color: #f56c6c;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: auto;
}

.cancel-btn:hover {
  background: #f56c6c;
  color: #fff;
  transform: scale(1.1);
}

.cancel-icon {
  font-size: 16px;
  font-style: normal;
  line-height: 1;
  font-weight: bold;
}

.custom-alert-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.18);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.custom-alert-box {
  background: #f7faff;
  border: 2px solid #409eff;
  border-radius: 14px;
  padding: 28px 32px 20px 32px;
  min-width: 220px;
  box-shadow: 0 4px 24px #409eff22;
  text-align: center;
  animation: alertIn 0.2s;
}

.custom-alert-content {
  color: #3076c9;
  font-size: 17px;
  margin-bottom: 18px;
  font-weight: bold;
  letter-spacing: 1px;
}

.custom-alert-btn {
  background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 32px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.custom-alert-btn:hover {
  background: linear-gradient(90deg, #3076c9 0%, #409eff 100%);
  transform: translateY(-1px);
}

@keyframes alertIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.rank-btn {
  position: absolute;
  top: 24px;
  right: 80px;
  background: linear-gradient(90deg, #e6a23c 0%, #f56c6c 100%);
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 10px 28px;
  cursor: pointer;
  font-size: 17px;
  font-weight: 700;
  box-shadow: 0 4px 16px #f56c6c33, 0 1.5px 0 #fff inset;
  transition: background 0.2s, box-shadow 0.2s, transform 0.1s;
  z-index: 10;
  letter-spacing: 1px;
  margin-left: 12px;
}

.rank-btn:hover {
  background: linear-gradient(90deg, #f56c6c 0%, #e6a23c 100%);
  box-shadow: 0 8px 24px #f56c6c44, 0 1.5px 0 #fff inset;
  transform: translateY(-2px) scale(1.03);
}

.rank-dialog-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.18);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3000;
}

.rank-dialog-box {
  background: #fff;
  border-radius: 14px;
  padding: 28px 32px 20px 32px;
  min-width: 280px;
  max-width: 90vw;
  box-shadow: 0 4px 24px #f56c6c22;
  text-align: center;
  position: relative;
  width: 340px;
  margin-top: -220px;
}

.rank-dialog-title {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 18px;
  letter-spacing: 1px;
}

.rank-dialog-close {
  position: absolute;
  top: 12px;
  right: 18px;
  background: none;
  border: none;
  font-size: 26px;
  color: #aaa;
  cursor: pointer;
  font-weight: bold;
  transition: color 0.2s;
}

.rank-dialog-close:hover {
  color: #f56c6c;
}

.rank-dialog-list {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 340px;
  overflow-y: auto;
  text-align: left;
}

.rank-dialog-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  padding: 9px 0;
  border-bottom: 1px solid #f0f0f0;
}

.rank-dialog-item:last-child {
  border-bottom: none;
}

.rank-dialog-index {
  width: 28px;
  text-align: center;
  font-weight: bold;
  color: #aaa;
}

.rank-dialog-item.top1 .rank-dialog-index {
  color: #e6a23c;
}

.rank-dialog-item.top2 .rank-dialog-index {
  color: #b3b3b3;
}

.rank-dialog-item.top3 .rank-dialog-index {
  color: #cd7f32;
}

.rank-dialog-username {
  flex: 1;
  color: #409eff;
  font-weight: 500;
}

.rank-dialog-money {
  color: #f56c6c;
  font-weight: bold;
}
</style>
